package com.whz.gateway.configure;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
import com.whz.gateway.handler.GlobalWebExceptionHandler;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * 全局异常处理配置器
 *
 * @author whz
 */
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class CustomErrorAutoConfigure {

    @Resource
    private ServerProperties serverProperties;

    @Resource
    private ApplicationContext applicationContext;

    @Resource
    private ResourceProperties resourceProperties;

    @Resource
    private ObjectProvider<ViewResolver> viewResolvers;


    @Bean
    @Order(-1)
    @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ServerCodecConfigurer serverCodecConfigurer) {
        GlobalWebExceptionHandler exceptionHandler = new GlobalWebExceptionHandler(
                new DefaultErrorAttributes(),
                resourceProperties,
                this.serverProperties.getError(),
                applicationContext);

        exceptionHandler.setViewResolvers(this.viewResolvers.stream().collect(Collectors.toList()));
        exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }
}